package com.pansoft.kline.fragment;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseLazyFragment;
import com.efounder.util.AppContext;
import com.efounder.util.ToastUtil;
import com.efounder.utils.JfResourceUtil;
import com.efounder.utils.ResStringUtil;
import com.google.gson.Gson;
import com.pansoft.kline.activity.TransactionTrendActivity;
import com.pansoft.kline.adapter.KlineOptionalOrMVAdapter;
import com.pansoft.kline.greendao.DaoSessionUtil;
import com.pansoft.kline.greendao.SelfSelectedBeanDao;
import com.pansoft.kline.helper.BtcKanConfigAndRateHelper;
import com.pansoft.kline.model.ConfigCoinBean;
import com.pansoft.kline.model.ConfigMarketBean;
import com.pansoft.kline.model.ConfigSiteBean;
import com.pansoft.kline.model.KLineMarketValueModel;
import com.pansoft.kline.model.KlineOptionalOrMVModel;
import com.pansoft.kline.model.MarketMenuBean;
import com.pansoft.kline.model.SelfSelectRefreshEvent;
import com.pansoft.kline.model.SelfSelectedBean;
import com.pansoft.kline.util.KLineUtil;
import com.pansoft.kline.util.MarketNumberUtils;
import com.pansoft.kline.util.SelfSelectUtils;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.manager.CurrencyAndBourseManager;
import com.pansoft.openplanet.util.TCMathUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.utilcode.util.SPUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.MediaType;
import okhttp3.RequestBody;

import static com.pansoft.openplanet.constant.MarketConstant.KEY_MARKET_CATEGORY_VERSION;
import static com.pansoft.openplanet.constant.MarketConstant.MARKET_SELF_CHOOSE_URL;
import static com.pansoft.openplanet.constant.MarketConstant.MARKET_VALUE_URL;

/**
 * @author : zzj
 * @e-mail : zhangzhijun@pansoft.com
 * @date : 2018/11/19 9:23
 * @desc :  自选和市值的fragment
 * @version: 1.0
 */
public class KlineOptionalOrMVFragment extends BaseLazyFragment {

    private final static String TAG = "KlineOptionalOrMVFragment";

    public final static String CONVERSION_UNIT_VALUE_TEN_SHOUSAND = "10000";
    public final static String CONVERSION_UNIT_VALUE_POINT = "0.00";
    public final static String CONVERSION_UNIT_VALUE_Y = "100000000";

    private RecyclerView recycler;
    private SmartRefreshLayout refreshLayout;
    private KlineOptionalOrMVAdapter adapter;
    private List<KlineOptionalOrMVModel> klineOptionalOrMVModels = new ArrayList<>();
    private List<MarketMenuBean.DataBean.TickersBean> lastTickersBeans = new ArrayList<>();
    private List<KLineMarketValueModel.DataBean.CapsBean> lastCapsBeanList = new ArrayList<>();
    private Timer timer;
    private RefreshTask timerTask;
    private MarketMenuBean.DataBean.CategoryBean.ListBean menuBean;
    private int page = 1;

    private boolean isThreadRun = false;
    private boolean isUpLoad = false;
    /**
     * 市值item左上角的值
     */
    private int marketIndex = 0;

    public static KlineOptionalOrMVFragment newInstance(MarketMenuBean.DataBean.CategoryBean.ListBean bean) {

        Bundle args = new Bundle();
        args.putSerializable("bean", bean);
        KlineOptionalOrMVFragment fragment = new KlineOptionalOrMVFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.kline_fragment_optional_or_mv, null);
        menuBean = (MarketMenuBean.DataBean.CategoryBean.ListBean) getArguments().getSerializable("bean");
        initView(root);
        initListener();
        registerForContextMenu(recycler);
        EventBus.getDefault().register(this);
        return root;
    }

    @Override
    protected void onFirstInit() {
        super.onFirstInit();
        refreshLayout.autoRefresh();
        startTask();
    }

    /**
     * 数据请求
     */
    private void initData() {
        if (menuBean.getTitle().equals(_mActivity.getResources().getString(R.string.open_planet_btckan_menu1))) {
            remoteOptionalData();
        } else if (menuBean.getTitle().equals(_mActivity.getResources().getString(R.string.open_planet_btckan_menu2))) {
            remoteMarketValue(page);
        }
    }

    void initListener() {
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                initData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                isUpLoad = true;
                initData();
            }
        });
        /**
         * 列表点击事件
         */
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                TransactionTrendActivity.start(_mActivity, klineOptionalOrMVModels.get(position).getMarketId());
            }
        });

    }


    private void remoteMarketValue(int page) {
//        https://x.szsing.com:443/v2/quote/index/m_caps?page_size=20&page=1
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("page_size", "20");
        hashMap.put("page", page + "");
        JFCommonRequestManager.getInstance(getActivity()).requestGetByAsyn(TAG, MARKET_VALUE_URL, hashMap, new JFCommonRequestManager.ReqCallBack<String>() {
            @Override
            public void onReqSuccess(String result) {
                isUpLoad = false;
                refreshLayout.finishRefresh();
                refreshLayout.finishLoadMore();
                try {
                    KLineMarketValueModel marketMenuBean = new Gson().fromJson(result, KLineMarketValueModel.class);
                    if (marketMenuBean.getCode() != 0) {
                        ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail);
                        return;
                    }
                    disposeMarketValueData(marketMenuBean);
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail);

                }
            }


            @Override
            public void onReqFailed(String errorMsg) {
                isUpLoad = false;
                refreshLayout.finishRefresh();
                refreshLayout.finishLoadMore();
                ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail_abnormal);
            }
        });
    }

    /**
     * 处理市值的数据结构
     *
     * @param marketValueModel
     */
    private void disposeMarketValueData(KLineMarketValueModel marketValueModel) {
        List<KLineMarketValueModel.DataBean.CapsBean> capsBeans = marketValueModel.getData().getCaps();
//        if (lastCapsBeanList.size() == 0) {
//            lastCapsBeanList.addAll(capsBeans);
//        }
        if (capsBeans.size() != 0) {
            if (page == 1) {
                marketIndex = 0;
//                if(!isUpLoad){
//                    if(klineOptionalOrMVModels.size()!=0){
//                        for(int i = 0;i<10;i++){
//                            KlineOptionalOrMVModel klineOptionalOrMVModel = klineOptionalOrMVModels.get(i);
//                            KLineMarketValueModel.DataBean.CapsBean capsBean = capsBeans.get(i);
//                            KlineOptionalOrMVModel tempModel =  getModel(capsBean,i+1);
//                            klineOptionalOrMVModel.setChangeRate(tempModel.getChangeRate());
//                            klineOptionalOrMVModel.setNum(tempModel.getNum());
//                            klineOptionalOrMVModel.setName(tempModel.getName());
//                            klineOptionalOrMVModel.setIncrease(tempModel.isIncrease());
//                            klineOptionalOrMVModel.setSubPrice(tempModel.getSubPrice());
//                            klineOptionalOrMVModel.setTitle(tempModel.getTitle());
//                            klineOptionalOrMVModel.setPrice(tempModel.getPrice());
//
//                        }
//                        adapter.notifyDataSetChanged();
//                        return;
//                    }
//                }
                klineOptionalOrMVModels.clear();
            }
            for (int i = 0; i < capsBeans.size(); i++) {
//                if(!isThreadRun){
                marketIndex++;
//                }
                KLineMarketValueModel.DataBean.CapsBean capsBean = capsBeans.get(i);
//                KLineMarketValueModel.DataBean.CapsBean lastCapsBean = lastCapsBeanList.get(i);

                klineOptionalOrMVModels.add(getModel(capsBean, null, marketIndex));

            }
//            lastCapsBeanList.clear();
//            lastCapsBeanList.addAll(capsBeans);
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * 请求自选数据
     */
    String[] coins = new String[]{"920", "954", "958", "479", "410", "482", "277", "2698", "3819", "3669", "41", "75", "7505", "254", "285"};

    private void getSelfSelectedBean() {
        SelfSelectedBeanDao selfSelectedBeanDao = DaoSessionUtil.getInstance()
                .getSelfSelectedBeanDao();
        List<SelfSelectedBean> list = selfSelectedBeanDao.queryBuilder().
                where(SelfSelectedBeanDao.Properties.UserName.eq(EnvironmentVariable.getUserName())).list();
        if (list.size() <= 0) {
            for (int i = 0; i < coins.length; i++) {
                try {
                    SelfSelectedBean selfSelectedBean = new SelfSelectedBean();
                    selfSelectedBean.setUserName(EnvironmentVariable.getUserName());
                    selfSelectedBean.setMarketId(coins[i]);
                    selfSelectedBeanDao.insert(selfSelectedBean);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void remoteOptionalData() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("category_version", SPUtils.getInstance().getString(KEY_MARKET_CATEGORY_VERSION) + "");
        getSelfSelectedBean();
        StringBuilder marketIds = new StringBuilder();
        List<SelfSelectedBean> list = DaoSessionUtil.getInstance().getSelfSelectedBeanDao().queryBuilder().
                where(SelfSelectedBeanDao.Properties.UserName.eq(EnvironmentVariable.getUserName())).list();
        for (SelfSelectedBean s :
               list ) {
            marketIds.append(String.valueOf(s.getMarketId())).append(",");
        }
        if (list.size() > 0) {
            marketIds.deleteCharAt(marketIds.length() - 1);
        }
        hashMap.put("market_ids", "[" + marketIds + "]");
        String json = null;
        try {
            json = new JSONObject(hashMap.toString()).toString();

            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            RequestBody requestBody = RequestBody.create(JSON, json);
            JFCommonRequestManager.getInstance(getActivity()).requestPostByAsyncWithRequsetBody(TAG, MARKET_SELF_CHOOSE_URL, requestBody, new JFCommonRequestManager.ReqCallBack<String>() {
                @Override
                public void onReqSuccess(String result) {
                    refreshLayout.finishRefresh();
                    try {
                        MarketMenuBean marketMenuBean = new Gson().fromJson(result, MarketMenuBean.class);
                        if (marketMenuBean.getCode() != 0) {
                            ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail);
                            return;
                        }
                        disposeOptionalData(marketMenuBean);
                    } catch (Exception e) {
                        e.printStackTrace();
                        ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail);

                    }
                }

                @Override
                public void onReqFailed(String errorMsg) {
                    refreshLayout.finishRefresh();
                    ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail_abnormal);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onSelfSelectRefresh(SelfSelectRefreshEvent event) {
        SelfSelectRefreshEvent stickyEvent = EventBus.getDefault().removeStickyEvent(SelfSelectRefreshEvent.class);
        // Better check that an event was actually posted before
        if(stickyEvent != null) {
            // Now do something with it
            remoteOptionalData();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 处理自选数据
     */
    private void disposeOptionalData(MarketMenuBean marketMenuBean) {
        //获取自选的集合数据
        List<MarketMenuBean.DataBean.TickersBean> tickersBeans = marketMenuBean.getData().getTickers();
        if (lastTickersBeans.size() == 0) {
            lastTickersBeans.addAll(tickersBeans);
        }
        if (tickersBeans.size() != 0) {
            klineOptionalOrMVModels.clear();
            for (int i = 0; i < tickersBeans.size(); i++) {
                if (i >= lastTickersBeans.size()) {
                    continue;
                }
                MarketMenuBean.DataBean.TickersBean tickersBean = tickersBeans.get(i);
                MarketMenuBean.DataBean.TickersBean lastTickersBean = lastTickersBeans.get(i);
                KlineOptionalOrMVModel klineOptionalOrMVModel = new KlineOptionalOrMVModel();
                //根据marketId查找币的名字
                ConfigMarketBean configMarketBean = DaoSessionUtil.getInstance().getConfigMarketBeanDao().load(tickersBeans.get(i).getId());
                if (configMarketBean == null) {
                    continue;
                }
                klineOptionalOrMVModel.setMarketId(tickersBean.getId());
                klineOptionalOrMVModel.setName(configMarketBean.getCoin());
                //查找对应的信息
//                            ConfigCoinBean configCoinBean = DaoMaster.getDaoSessionInstance().getConfigCoinBeanDao().load(listBeans.get(j).getTitle());
//                LogUtils.e("获取到的币的信息---ConfigMarketBean-》" + configMarketBean.getCoin() + "----" + configMarketBean.getSite() +
//                        "---->" + configMarketBean.getCurrency() + "-----" + configMarketBean.getType());

                //根据查到的site查找site的title
                ConfigSiteBean configSiteBean = DaoSessionUtil.getInstance().getConfigSiteBeanDao().load(configMarketBean.getSite());
//                LogUtils.e("获取到的币的信息---configSiteBean-》" + configSiteBean.getTitle() + "----" + configSiteBean.getFee() +
//                        "---->" + configSiteBean.getUrl() + "-----" + configSiteBean.getUniqueKey());
                //根据查到的coin获取coins
                ConfigCoinBean configCoinBean = DaoSessionUtil.getInstance().getConfigCoinBeanDao().load(configMarketBean.getCoin());
//                LogUtils.e("获取到的币的信息---configCoinBean-》" + configCoinBean.getTitle() + "----" + configCoinBean.getName() +
//                        "---->" + configCoinBean.getCoin_name_other() + "-----" + configCoinBean.getSymbol());
                JSONObject rateObject = BtcKanConfigAndRateHelper.getRate(null);
                String rate = null;
                try {
                    rate = rateObject.getJSONObject(configMarketBean.getSite()).getString(configMarketBean.getCurrency());
//                    String rateRmb = rateObject.getJSONObject(configMarketBean.getSite()).getString("CNY");
                    String rateRmb = rateObject.getJSONObject(configMarketBean.getSite()).getString(CurrencyAndBourseManager.getCurrencyUnitCode());
                    double value = TCMathUtil.mul((tickersBean.getLast() / Double.valueOf(rate)) + "", rateRmb);
                    klineOptionalOrMVModel.setTitle(configSiteBean.getTitle() + "," + configCoinBean.getTitle());
                    klineOptionalOrMVModel.setPrice(CurrencyAndBourseManager.getNowCurrencySymbol() + value);

                    //将double数据转换为正常数据显示  不适用科学计数法  new BigDecimal(tickersBean.getLast()+"").toPlainString()
                    klineOptionalOrMVModel.setSubPrice(KLineUtil.getCurrencySymbol(configMarketBean.getCurrency()) + new BigDecimal(tickersBean.getLast() + "").toPlainString() + "");
//                    klineOptionalOrMVModel.setNum(configMarketBean.getCurrency() + " 量 " + conversion(tickersBeans.get(i).getVol() + "", CONVERSION_UNIT_VALUE_TEN_SHOUSAND, CONVERSION_UNIT_VALUE_POINT) + "万");
                    klineOptionalOrMVModel.setNum(configMarketBean.getCurrency() + " "+_mActivity.getResources().getString(R.string.chart_kline_optional_amount)+" " +
                            MarketNumberUtils.amountConversion(tickersBean.getVol()));
                    //计算涨跌幅的百分比   （last-open）/open*100
                    double changeRate = (tickersBean.getLast() - tickersBean.getOpen()) / tickersBean.getOpen() * 100;
                    //如果大于0涨  小于0跌
                    if (changeRate > 0) {
                        klineOptionalOrMVModel.setIncrease(true);
                        klineOptionalOrMVModel.setChangeRate("+" + KLineUtil.conversion(changeRate + "", "1", "0.00") + "%");
                    } else {
                        klineOptionalOrMVModel.setIncrease(false);
                        klineOptionalOrMVModel.setChangeRate(KLineUtil.conversion(changeRate + "", "1", "0.00") + "%");
                    }
                    if (tickersBean.getLast() > lastTickersBean.getLast()) {
                        klineOptionalOrMVModel.setTrendType(1);
                        tickersBean.setLastTrendType(1);
                    } else if (lastTickersBean.getLast() > tickersBean.getLast()) {
                        klineOptionalOrMVModel.setTrendType(-1);
                        tickersBean.setLastTrendType(-1);
                    } else {
                        klineOptionalOrMVModel.setTrendType(lastTickersBean.getLastTrendType());
                        tickersBean.setLastTrendType(lastTickersBean.getLastTrendType());
                    }
                    klineOptionalOrMVModels.add(klineOptionalOrMVModel);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            lastTickersBeans.clear();
            lastTickersBeans.addAll(tickersBeans);
            adapter.notifyDataSetChanged();
        }


    }

    /**
     * 解析数据model
     *
     * @param capsBean
     * @return
     */
    private KlineOptionalOrMVModel getModel(KLineMarketValueModel.DataBean.CapsBean capsBean, KLineMarketValueModel.DataBean.CapsBean lastCapsBean, int index) {
        KlineOptionalOrMVModel klineOptionalOrMVModel = new KlineOptionalOrMVModel();
        klineOptionalOrMVModel.setMarketId(capsBean.getTicker().getId());
        //根据marketId查找币的名字
        ConfigMarketBean configMarketBean = DaoSessionUtil.getInstance().getConfigMarketBeanDao().load(capsBean.getTicker().getId());
        klineOptionalOrMVModel.setName(configMarketBean.getCoin());
        //查找对应的信息
//                            ConfigCoinBean configCoinBean = DaoMaster.getDaoSessionInstance().getConfigCoinBeanDao().load(listBeans.get(j).getTitle());
//                LogUtils.e("获取到的币的信息---ConfigMarketBean-》" + configMarketBean.getCoin() + "----" + configMarketBean.getSite() +
//                        "---->" + configMarketBean.getCurrency() + "-----" + configMarketBean.getType());

        //根据查到的site查找site的title
//                ConfigSiteBean configSiteBean = DaoSessionUtil.getInstance().getConfigSiteBeanDao().load(configMarketBean.getSite());
//                LogUtils.e("获取到的币的信息---configSiteBean-》" + configSiteBean.getTitle() + "----" + configSiteBean.getFee() +
//                        "---->" + configSiteBean.getUrl() + "-----" + configSiteBean.getUniqueKey());
        //根据查到的coin获取coins
        ConfigCoinBean configCoinBean = DaoSessionUtil.getInstance().getConfigCoinBeanDao().load(configMarketBean.getCoin());
//                LogUtils.e("获取到的币的信息---configCoinBean-》" + configCoinBean.getTitle() + "----" + configCoinBean.getName() +
//                        "---->" + configCoinBean.getCoin_name_other() + "-----" + configCoinBean.getSymbol());
        JSONObject rateObject = BtcKanConfigAndRateHelper.getRate(null);
        String rate = null;
        try {
            rate = rateObject.getJSONObject(configMarketBean.getSite()).getString(configMarketBean.getCurrency());
//            String rateRMB = rateObject.getJSONObject(configMarketBean.getSite()).getString("CNY");
            String rateRMB = rateObject.getJSONObject(configMarketBean.getSite()).getString(CurrencyAndBourseManager.getCurrencyUnitCode());

            double value = TCMathUtil.mul((capsBean.getTicker().getLast() / Double.valueOf(rate)) + "", rateRMB);
            //使用cap字段乘以汇率 总的价值
            String marketValue = ((capsBean.getCap() / Double.valueOf(rate)) * Double.valueOf(rateRMB)) + "";
            klineOptionalOrMVModel.setTitle(_mActivity.getResources().getString(R.string.chart_kline_optional_market_value_and_title,
                    index+"",CurrencyAndBourseManager.getCurrencyUnitCode(), MarketNumberUtils.amountConversion(Double.valueOf(marketValue)),configCoinBean.getTitle()));
            klineOptionalOrMVModel.setPrice(CurrencyAndBourseManager.getNowCurrencySymbol() + value);
            klineOptionalOrMVModel.setSubPrice("$" + capsBean.getTicker().getLast() + "");

            klineOptionalOrMVModel.setNum(_mActivity.getResources().getString(R.string.chart_kline_optional_24H_amount)+" " +
                    MarketNumberUtils.amountConversion(capsBean.getTicker().getVol()));

            //计算涨跌幅的百分比   （last-open）/open*100
            double changeRate = (capsBean.getTicker().getLast() - capsBean.getTicker().getOpen()) / capsBean.getTicker().getOpen() * 100;
            //如果大于0涨  小于0跌
            if (changeRate > 0) {
                klineOptionalOrMVModel.setIncrease(true);
                klineOptionalOrMVModel.setChangeRate("+" + KLineUtil.conversion(changeRate + "", "1", "0.00") + "%");
            } else {
                klineOptionalOrMVModel.setIncrease(false);
                klineOptionalOrMVModel.setChangeRate(KLineUtil.conversion(changeRate + "", "1", "0.00") + "%");
            }
//            if (capsBean.getTicker().getLast() > lastCapsBean.getTicker().getLast()) {
//                klineOptionalOrMVModel.setTrendType(1);
//                capsBean.setLastTrendType(1);
//            } else if (lastCapsBean.getTicker().getLast() > capsBean.getTicker().getLast()) {
//                klineOptionalOrMVModel.setTrendType(-1);
//                capsBean.setLastTrendType(-1);
//            } else {
//                klineOptionalOrMVModel.setTrendType(lastCapsBean.getLastTrendType());
//                capsBean.setLastTrendType(lastCapsBean.getLastTrendType());
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return klineOptionalOrMVModel;
    }

    private void startTask() {
        stopTask();
        timer = new Timer();
        timerTask = new RefreshTask();
        timer.schedule(timerTask, 0, 5000);
    }

    private void stopTask() {
        if (timer != null) {
            timer.cancel();
            timer.purge();
            timer = null;
            timerTask = null;
        }
    }


    private void initView(final View root) {
        recycler = root.findViewById(R.id.recycler);
        refreshLayout = root.findViewById(R.id.refreshLayout);
        //自选禁止上拉加载，，市值可以上拉加载
        if (menuBean.getTitle().equals(ResStringUtil.getString(R.string.open_planet_btckan_menu1))) {
            refreshLayout.setEnableLoadMore(false);
        } else if (menuBean.getTitle().equals(ResStringUtil.getString(R.string.open_planet_btckan_menu2))) {
            refreshLayout.setEnableLoadMore(true);
        }
        recycler.setLayoutManager(new LinearLayoutManager(_mActivity));
        //添加自定义分割线
        DividerItemDecoration divider = new DividerItemDecoration(_mActivity, DividerItemDecoration.VERTICAL);
        divider.setDrawable(JfResourceUtil.getSkinDrawable( R.drawable.kline_shape_recycler_divider));
        recycler.addItemDecoration(divider);
        adapter = new KlineOptionalOrMVAdapter(R.layout.kline_item_optional_or_mv, klineOptionalOrMVModels);
        recycler.setAdapter(adapter);

    }

    //    @Override
//    public void onHiddenChanged(boolean hidden) {
//        super.onHiddenChanged(hidden);
//        if(hidden){
//            stopTask();
//        }else {
//            startTask();
//        }
//    }


    @Override
    public void onResume() {
        super.onResume();
        if (getUserVisibleHint() == true) {
            startTask();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        stopTask();
    }

    @Override
    protected void DestroyView() {
        stopTask();
    }

    @Override
    protected void onUserVisible() {
        startTask();
    }

    @Override
    protected void onUserInvisible() {
        stopTask();
    }

    public class RefreshTask extends TimerTask {

        @Override
        public void run() {
            if (menuBean.getTitle().equals("自选")) {
                remoteOptionalData();
            } else if (menuBean.getTitle().equals("市值")) {
                remoteMarketValue(1);
            }

        }
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if (getUserVisibleHint()) {
            int clickedItemPosition = item.getOrder();
            String marketId = klineOptionalOrMVModels.get(clickedItemPosition).getMarketId();
            long id = SelfSelectUtils.getIsSelectedId(marketId);
            if (id != -1) {
                SelfSelectedBean selfSelectedBean = new SelfSelectedBean();
                selfSelectedBean.setUserName(EnvironmentVariable.getUserName());
                selfSelectedBean.setMarketId(marketId);
                selfSelectedBean.setId(id);
                DaoSessionUtil.getInstance().getSelfSelectedBeanDao()
                        .delete(selfSelectedBean);
            } else {
                SelfSelectedBean selfSelectedBean = new SelfSelectedBean();
                selfSelectedBean.setMarketId(marketId);
                selfSelectedBean.setUserName(EnvironmentVariable.getUserName());
                DaoSessionUtil.getInstance().getSelfSelectedBeanDao()
                        .insert(selfSelectedBean);
            }
            EventBus.getDefault().postSticky(new SelfSelectRefreshEvent());
            return true;
        }
        return false;
    }
}
